﻿@inherits LayoutComponentBase
@implements IDisposable
@namespace BootstrapBlazor.Components
@using AdminBlazor.Infrastructure.Encrypt
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Http
@using Microsoft.AspNetCore.Http.Extensions

<BootstrapBlazorRoot>
    <Layout Menus="@menus" ShowGotoTop="true" ShowCollapseBar="true" SideWidth="0"
            IsPage="true" IsFullSide="true" IsFixedHeader="true" 
            TabDefaultUrl="/Admin" UseTabSet="true" AdditionalAssemblies="@AppDomain.CurrentDomain.GetAssemblies()">
        <Header>
            <div class="ms-3 flex-sm-fill d-none d-sm-block">
                @if (admin.CurrentMenu != null)
                {
                    <ol class="breadcrumb m-0 p-0">
                        <li class="breadcrumb-item">主页</li>
                        @if (admin.CurrentMenu.Parent != null)
                        {
                            <li class="breadcrumb-item">@admin.CurrentMenu.Parent.Label</li>
                        }
                        <li class="breadcrumb-item active" aria-current="page">@admin.CurrentMenu?.Label</li>
                    </ol>
                }
            </div>
            <div class="flex-fill d-sm-none">
                
            </div>
            @if (admin?.User != null)
            {
                <Logout ImageUrl="logo.png" DisplayName="@admin.User.Username" UserName="@admin.Roles.FirstOrDefault()?.Name" class="">
                    <HeaderTemplate>
                        <div class="d-flex flex-fill align-items-center">
                            <img alt="avatar" src="logo.png" style="border-radius: 50%;">
                            <div class="flex-fill">
                                <div class="logout-dn">@admin.User.Username</div>
                                <div class="logout-un">@admin.Roles.FirstOrDefault()?.Description</div>
                            </div>
                        </div>
                    </HeaderTemplate>
                    <LinkTemplate>
                        <a @onclick="TogglePwdModal" href="javascript:;"><i class="fa-solid fa-key"></i><span>修改密码</span></a>
                        <a @onclick="LogoutClick" href="/Admin/Login"><i class="fa-solid fa-arrow-right-to-bracket"></i><span>注销</span></a>
                    </LinkTemplate>
                </Logout>
                
            }
        </Header>
        <Side>
            <div class="layout-banner">
                <img class="layout-logo" src="logo.png" />
                <div class="layout-title">
                    <span><a href="/?clear=cache" target="_blank">@admin.Tenant?.Title</a></span>
                </div>
            </div>
        </Side>
        <Main>
            <CascadingValue Value="this" IsFixed="true">
                @if (admin.AuthPathSuccess)
                {
                    @Body
                }
            </CascadingValue>
            
        </Main>
    </Layout>

    <Modal @ref="Modal" IsKeyboard="true" style="z-index:2050;">
        <ModalDialog Title="修改密码" ShowSaveButton="true" CloseButtonText="取消" Size="Size.Medium" OnSaveAsync="OnSavePasswordAsync">
            <BodyTemplate>
                <EditForm EditContext="@context">
                    <DataAnnotationsValidator />
                    <div class="row">
                        <div class="form-group col-12">
                            <label class="form-label">旧密码</label>
                            <InputText @bind-Value="Model.OldPassword" type="password" class="form-control" placeholder="" maxlength="30" />
                            <ValidationMessage For="()=>Model.OldPassword" />
                        </div>
                        <div class="form-group col-12">
                            <label class="form-label">新密码</label>
                            <InputText @bind-Value="Model.NewPassword" type="password" class="form-control" placeholder="" maxlength="30"/>
                            <ValidationMessage For="()=>Model.NewPassword" />
                        </div>
                        <div class="form-group col-12">
                            <label class="form-label">确认新密码</label>
                            <InputText @bind-Value="Model.ConfirmPassword" type="password" class="form-control" placeholder="" maxlength="30"/>
                            <ValidationMessage For="()=>Model.ConfirmPassword" />
                        </div>
                    </div>
                </EditForm>
            </BodyTemplate>
        </ModalDialog>
    </Modal>
</BootstrapBlazorRoot>

@code {
    [Inject] AdminContext admin { get; set; }
    List<MenuItem> menus { get; set; }

    static Modal? Modal;

    private UserPassword? Model { get; set; } = new UserPassword();

    async Task LogoutClick()
    {
        await admin.SignOut();
        admin.RedirectLogin();
    }

    EditContext context;

    async protected override Task OnInitializedAsync()
    {
        await admin.Init();
        if (!await admin.AuthPath(new Uri(nav.Uri).AbsolutePath))
        {
            if (admin.User != null)
            {
                //没有访问权限.
            }
            else
            {
                admin.RedirectLogin();
                return;
            }
        }

        var data = admin.RoleMenus.Where(a => new[] { MenuEntityType.菜单, MenuEntityType.增删改查 }.Contains(a.Type)).OrderBy(a => a.Sort).ToList();
        menus = new List<MenuItem>();
        foreach (var item1 in data.Where(x => x.ParentId == 0))
        {
            List<MenuItem> menusubs = new List<MenuItem>();
            foreach (var item2 in data.Where(x => x.ParentId == item1.Id))
            {
                menusubs.Add(new MenuItem { Text = item2.Label, Url = item2.Path });
            }

            menus.Add(new MenuItem { Text = item1.Label, Url = item1.Path, Items = menusubs, Icon = "fas " + item1.Icon.IsNull("fa-laptop") });
        }

        context = new EditContext(Model);
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (!firstRender) return;
        if (admin.Tenant == null) await JS.Error("租户信息错误.");
        if (admin.Roles?.Any() == false) await JS.Error("没有访问权限: 未分配角色.");
        else if (!admin.AuthPathSuccess) await JS.Error("没有访问权限.");

        locationChangingHandler = nav.RegisterLocationChangingHandler(async e =>
        {
            var uri = nav.ToAbsoluteUri(e.TargetLocation);
            if (!await admin.AuthPath(uri.AbsolutePath))
                await JS.Error("没有访问权限.");
        });
    }

    void TogglePwdModal()
    {
        Modal.Toggle();
    }

    async Task<bool> OnSavePasswordAsync()
    {
        if (context.Validate())
        {
            if(await admin.UpdatePassword(admin.User, Model))
            {
                await JS.Success("密码修改成功！.");
                Modal = new Modal();
                return true;
            }

            await JS.Error("密码修改失败，请确认原密码是否正确！.");
        }

        return false;
    }

    IDisposable locationChangingHandler;
    public void Dispose() => locationChangingHandler?.Dispose();
}